<template>
	<xn-form-container title="新增还款记录" :width="550" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="所属项目" name="projectCode">
				<ProjectSelect v-model:value="formData.projectCode" @change="handleProjectChange" />
			</a-form-item>
			<a-form-item label="所属批次" name="batch">
				<a-select v-model:value="formData.batch" placeholder="请选择所属批次">
					<a-select-option v-for="option in batchList" :key="option.batch" :value="option.batch" :label="option.batch">
						{{ option.batch }}
					</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="所属公司" name="deptId">
				<DeptSelect v-model:value="formData.deptId" />
			</a-form-item>
			<a-form-item label="还款时间" name="repaymentDate">
				<a-date-picker
					v-model:value="formData.repaymentDate"
					value-format="YYYY-MM-DD"
					placeholder="请选择还款时间"
					style="width: 100%"
				/>
			</a-form-item>
			<a-form-item label="还款金额" name="repaymentAmount">
				<a-input-number
					v-model:value="formData.repaymentAmount"
					:min="0"
					:precision="2"
					placeholder="请输入还款金额"
					style="width: 100%"
				/>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-space>
				<a-button @click="onClose">关闭</a-button>
				<a-button type="primary" @click="handleSubmit" :loading="submitting"> 保存</a-button>
			</a-space>
		</template>
	</xn-form-container>
</template>
<script setup>
	import { ref } from 'vue'
	import { required } from '@/utils/formRules'
	import ProjectSelect from '@/components/Tjzy/Project/index.vue'
	import subsidiaryRepaymentApi from '@/api/bi/repayment/subsidiary/subsidiaryRepaymentApi'
	import monthlyApi from '@/api/bi/goals/monthly/monthlyApi'
	import dayjs from 'dayjs'
	import DeptSelect from '@/components/Tjzy/Dept/index.vue'

	// 组件状态
	const visible = ref(false)
	const submitting = ref(false)
	const formRef = ref()
	const batchList = ref([])
	// 使用ref创建表单数据
	const formData = ref({
		projectCode: '',
		batch: '',
		deptId: '',
		repaymentDate: null,
		repaymentAmount: null
	})

	// 表单验证规则
	const formRules = {
		projectCode: [required('请选择项目')],
		batch: [required('请选择批次')],
		deptId: [required('请输入欠款人用户编号')],
		repaymentDate: [required('请选择还款时间')],
		repaymentAmount: [required('请输入还款金额')]
	}

	// 打开表单
	const onOpen = (record) => {
		visible.value = true
		if (record) {
			formData.value = {
				...record,
				repaymentDate: record.repaymentDate || null,
				overdueDate: record.overdueDate || null
			}
		} else {
			resetForm()
		}
	}

	// 重置表单
	const resetForm = () => {
		formData.value = {
			companyCode: '',
			debtorUserNo: '',
			repaymentDate: null,
			repaymentAmount: null
		}
		formRef.value.clearValidate()
	}

	// 关闭表单
	const onClose = () => {
		resetForm()
		visible.value = false
	}

	// 公司选择变化
	const handleProjectChange = (val) => {
		formData.value.projectCode = val
		formRef.value.validateFields(['projectCode'])
		const obj = {
			current: 1,
			size: 10,
			projectCode: val,
			belongingMonth: dayjs().format('YYYYMM')
		}
		batchList.value = []
		formData.value.batch = undefined
		monthlyApi.pageList(obj).then((res) => {
			batchList.value = res.records.map((item) => ({
				batch: item.batchNumber
			}))
		})
	}

	// 提交表单
	const handleSubmit = async () => {
		try {
			submitting.value = true
			await formRef.value.validate()
			const submitData = {
				...formData.value,
				repaymentAmount: Number(formData.value.repaymentAmount)
			}
			await subsidiaryRepaymentApi.add(submitData)
			onClose()
			emit('successful')
		} catch (error) {
			console.error('提交失败:', error)
		} finally {
			submitting.value = false
		}
	}

	const emit = defineEmits(['successful'])
	defineExpose({ onOpen })
</script>
